package org.smart4j.chapter2.service;

import org.smart4j.chapter2.helper.DatabaseHelper;
import org.smart4j.chapter2.model.Customer;
import org.smart4j.chapter2.util.PropsUtil;

import java.sql.*;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class CustomerService {

    private static final String DRIVER;
    private static final String URL;
    private static final String USERNAME;
    private static final String PASSWORD;

    static {
        Properties conf = PropsUtil.loadProps("config.properties");
        DRIVER=conf.getProperty("jdbc.driver");
        URL=conf.getProperty("jdbc.url");
        USERNAME=conf.getProperty("jdbc.username");
        PASSWORD=conf.getProperty("jdbc.password");

        try{
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.getStackTrace();
        }
    }
    public List<Customer> getCustomerList() {
//        Connection conn=DatabaseHelper.getConnection();
//        try{
            String sql="select * from customer";
            return DatabaseHelper.queryEntityList(Customer.class, sql);
//        } finally {
//            DatabaseHelper.closeConnection(conn);
//        }
    }


//    public List<Customer> getCustomerList(String keyword) {
//        Connection conn=null;
//        try{
//            List<Customer> customerList=new ArrayList<Customer>();
//            String sql="select * from customer";
//            conn= DatabaseHelper.getConnection();
//            PreparedStatement stmt=conn.prepareStatement(sql);
//            ResultSet rs=stmt.executeQuery();
//            while (rs.next()) {
//                Customer customer=new Customer();
//                customer.setId(rs.getLong("id"));
//                customer.setName(rs.getString("name"));
//                customer.setContact(rs.getString("contact"));
//                customer.setTelephone(rs.getString("telephone"));
//                customer.setEmail(rs.getString("email"));
//                customer.setRemark(rs.getString("remark"));
//                customerList.add(customer);
//            }
//            return customerList;
//
//        }catch (Exception e) {
//            e.getStackTrace();
//        } finally {
//            DatabaseHelper.closeConnection(conn);
//        }
//        return null;
//    }
    public Customer getCustomer(long id) {
        //TODO
        return null;
    }
    /*创建客户*/
    public boolean createCustomer(Map<String,Object> fieldMap) {
        return DatabaseHelper.insertEntity(Customer.class,fieldMap);
    }
    /*更新客户*/
    public boolean updateCustomer(long id,Map<String,Object> fieldMap) {
        return DatabaseHelper.updateEntity(Customer.class,id,fieldMap);
    }
    /*删除客户*/
    public boolean deleteCustomer(long id) {
        return DatabaseHelper.deleteEntity(Customer.class,id);
    }
}
